package com.intct.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author : Felix
 * @Date : 2025.05.15 16:58
 * TODO :
 **/
public class JDBCUtil {

    public static Connection getMySqlConnection() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://192.168.199.185:3306/travel_config", "root", "999999");
    }

    public static void closeMySqlConnection(Connection connection) throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }

    public static <T> List<T> query(Connection connection, String sql, Class<T> clazz) throws Exception {
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        // 获取元数据(字段名称)
        ResultSetMetaData metaData = rs.getMetaData();

        List<T> objList = new ArrayList<>();

        while (rs.next()) {
            // Java反射，创建对象
            T obj = clazz.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = rs.getObject(i);

                // 把蛇形命名转为小驼峰命名
                String colName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
                //commons 包类
                BeanUtils.setProperty(obj, colName, value);
            }
            objList.add(obj);
            new RuntimeException();
        }
        return objList;
    }
}
